using System.Text.Json;
using FastEndpoints;
using Ke.Bee.Shared;
using Ke.Bee.Shared.Abstractions;
using Ke.Bee.Shared.Models;
using Ke.Bee.Transcription.Hubs;
using Ke.Paraleet.Hosts.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Serilog;

var API_BASE_URL = "/api";

// 创建并配置 Logger
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.File("logs/log-.txt",
        rollingInterval: RollingInterval.Day,
        retainedFileCountLimit: 30)
    .CreateLogger();

try
{
    Log.Information("Starting web application");
    var builder = WebApplication.CreateBuilder(args);

    // 注册 Serilog
    builder.Host.UseSerilog();

    var serv = builder.Configure();

    // Add services to the container.
    // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
    serv.AddOpenApi();
    serv.AddWebOptimizer();
    serv.AddEndpointsApiExplorer();
    serv.AddSignalR();
    serv.AddFastEndpoints();
    serv.Register();

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.MapOpenApi();
    }

    app.UseCors("AllowAll");
    app.UseWebOptimizer(); // WebOptimizer
    app.UseFileServer(new FileServerOptions
    {
        EnableDefaultFiles = true,
        EnableDirectoryBrowsing = false,
        DefaultFilesOptions =
    {
        DefaultFileNames = [ "index.html" ]
    }
    });

    //app.UseHttpsRedirection();

    // 使用请求日志中间件（可选）
    // app.UseSerilogRequestLogging();

    var appSettings = app.Services.GetRequiredService<IOptions<AppSettings>>().Value;

    // 应用配置信息
    app.MapGet($"{API_BASE_URL}/cfg", () => appSettings);

    /*
    app.MapPost($"{API_BASE_URL}/upload", async (HttpContext context, [FromServices] ITranscriptionService transcriptionService) =>
    {
        try
        {
            var form = await context.Request.ReadFormAsync();
            var file = form.Files["file"];

            if (file == null || file.Length == 0)
            {
                return Results.BadRequest(new { success = false, message = "未选择文件" });
            }

            // 验证文件类型
            var allowedExtensions = new[] { ".mp3", ".mp4", ".wav", ".avi", ".mov", ".flac", ".aac", ".wma", ".m4a" };
            var fileExtension = Path.GetExtension(file.FileName).ToLower();
            if (!allowedExtensions.Contains(fileExtension))
            {
                return Results.BadRequest(new { success = false, message = "不支持的文件格式" });
            }

            // 验证文件大小 (500MB)
            if (file.Length > 500 * 1024 * 1024)
            {
                return Results.BadRequest(new { success = false, message = "文件大小不能超过500MB" });
            }

            // 读取参数
            var language = form["language"].ToString() ?? "zh-CN";
            var model = form["model"].ToString() ?? "base";
            var sliceDuration = int.TryParse(form["sliceDuration"], out var sd) ? sd : 10;
            var silenceThreshold = int.TryParse(form["silenceThreshold"], out var st) ? st : 500;

            var request = new TranscriptionRequest
            {
                File = file,
                Language = language,
                Model = model,
                SliceDuration = sliceDuration,
                SilenceThreshold = silenceThreshold
            };

            var taskId = await transcriptionService.ProcessFileAsync(request);
            return Results.Ok(new { success = true, taskId });
        }
        catch (Exception ex)
        {
            return Results.Problem($"上传失败: {ex.Message}");
        }
    });

    app.MapGet("/api/task/{taskId}/progress", (string taskId, [FromServices] ITranscriptionService transcriptionService) =>
    {
        try
        {
            var progress = transcriptionService.GetTaskProgress(taskId);
            if (progress == -1)
            {
                return Results.NotFound(new { success = false, message = "任务不存在" });
            }

            return Results.Ok(new { success = true, progress });
        }
        catch (Exception ex)
        {
            return Results.Problem($"获取进度失败: {ex.Message}");
        }
    });
    */

    // 使用 FastEndpoints
    app.UseFastEndpoints(c =>
    {
        c.Endpoints.RoutePrefix = "api";
        c.Serializer.Options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    });

    // 启动后台清理任务
    //StartBackgroundCleanup(app);

    app.LaunchBrowser();
    // 映射Hub
    app.MapHub<TranscriptionHub>("/ws/transcription");

    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
    Log.CloseAndFlush();
}

// 后台清理任务
static void StartBackgroundCleanup(WebApplication app)
{
    var fileStorage = app.Services.GetRequiredService<IFileStorageService>();
    var logger = app.Services.GetRequiredService<ILogger<Program>>();

    // 每6小时清理一次超过24小时的临时文件
    _ = Task.Run(async () =>
    {
        while (true)
        {
            try
            {
                await fileStorage.CleanupOldFilesAsync(TimeSpan.FromHours(24), CancellationToken.None);
                await Task.Delay(TimeSpan.FromHours(6));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "后台清理任务失败");
                await Task.Delay(TimeSpan.FromMinutes(5));
            }
        }
    });
}